<template>
  <div class="goodsAll">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="container">
      <div class="box">
        <div class="sidebar">
          <el-steps direction="vertical" :active="activeKey" finish-status="success">
            <el-step :title="item" v-for="(item, index) in Steps" :key="index" :name="index+1" />
          </el-steps>
        </div>
        <div class="main">
          <el-form
            ref="FrominpRef"
            label-position="top"
            :model="Frominp"
            status-icon
            label-width="120px"
            :rules="rules"
          >
            <el-tabs
              @tab-change="checkthere"
              v-model="tabactivekey"
              :before-leave="beforeTabLeave"
              label-position="top"
            >
              <!-- 基本信息 -->
              <el-tab-pane label="基本信息" name="1">
                <el-form-item label="商品名称" prop="name">
                  <el-input
                    v-model="Frominp.name"
                    type="text"
                    autocomplete="off"
                    placeholder="请输入商品名称"
                  />
                </el-form-item>
                <el-form-item label="商品价格" prop="price">
                  <el-input v-model="Frominp.price" type="text" autocomplete="off" />
                </el-form-item>
                <el-form-item label="商品重量" prop="weight">
                  <el-input v-model="Frominp.weight" type="text" autocomplete="off" />
                </el-form-item>
                <el-form-item label="商品数量" prop="number">
                  <el-input v-model="Frominp.number" type="text" autocomplete="off" />
                </el-form-item>
                <el-form-item label="商品分类" prop="category">
                  <el-cascader
                    placeholder="请选择分类"
                    v-model="Frominp.category"
                    :options="cascader"
                    :props="cascaderprops"
                    @change="handleChange"
                  />
                </el-form-item>
                <el-form-item>
                  <!-- <el-button type="primary" @click="next(FrominpRef)">下一步</el-button> -->
                </el-form-item>
              </el-tab-pane>
              <!-- 商品参数 -->
              <el-tab-pane label="商品参数" name="2">
                <el-form-item
                  v-if="ManyList.length"
                  v-for="(item, index) in ManyList"
                  :key="index"
                  label-position="top"
                  :label="item.attr_name"
                >
                  <el-checkbox-group v-model="ManyAttrList">
                    <el-checkbox
                      border
                      :label="item"
                      v-for="(item, i) in item.attr_vals.split(' ')"
                      :key="i"
                    >{{ item }}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-alert v-else title="无可用参数" type="success" center :closable="false"></el-alert>
              </el-tab-pane>
              <!-- 商品属性 -->
              <el-tab-pane label="商品属性" name="3">
                <el-form-item
                  v-if="OnlyList.length"
                  v-for="item in OnlyList"
                  :label="item.attr_name"
                  :key="item.attr_id"
                >
                  <el-input v-model="item.attr_vals"></el-input>
                </el-form-item>
                <el-alert v-else title="无可用属性" type="success" center :closable="false"></el-alert>
              </el-tab-pane>
              <el-tab-pane label="商品图片" name="4">
                <el-upload
                  class="upload-img"
                  :action="uploadUrl"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  list-type="picture"
                  :headers="headersObj"
                  :on-success="handleSuccess"
                >
                  <el-button type="primary" class="uploadBtn">点击上传</el-button>
                </el-upload>
              </el-tab-pane>
              <el-tab-pane label="商品内容" name="5">
                <QuillEditor theme="snow" class="QuillEditor" v-model:content="Frominp.introduce" />
              </el-tab-pane>
              <el-tab-pane label="完成" name="6">
                <div class="subtitle" v-if="SubmitSay">
                  <p>你已经完成了提交</p>
                  <p>将在三秒后返回商品列表页面</p>
                </div>
                <div class="subtitle" v-else>
                  <p>也许你还没有完成信息填写</p>
                  <p>请填写完毕后再前往此页面进行提交吧</p>
                </div>
                <el-button type="primary" class="uploadBtn" @click="SubmitFrom(FrominpRef)">提交商品</el-button>
              </el-tab-pane>
            </el-tabs>
          </el-form>
        </div>
      </div>
    </div>
    <el-dialog title="图片预览" v-model="previewDialogVisible" width="50%">
      <img :src="previewPath" alt class="perviewImg" />
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, ref, onBeforeMount, computed } from "vue";
import {
  getCategories,
  getCateAttrs,
  uploadUrl,
  postaddGoods
} from "../tools/ajax.js";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { QuillEditor } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
const route = useRoute();
const router = useRouter();
const activeKey = ref(0);
const tabactivekey = computed(() => {
  return (activeKey.value + 1).toString();
});
const Steps = [
  "基本信息",
  "商品参数",
  "商品属性",
  "商品图片",
  "商品内容",
  "完成"
];
// 自定义校验规则
const rules = {
  name: {
    required: true,
    message: "名称不能为空",
    trigger: "change"
  },
  price: {
    required: true,
    message: "价格不能为空",
    trigger: "change"
  },
  weight: {
    required: true,
    message: "重量不能为空",
    trigger: "change"
  },
  number: {
    required: true,
    message: "数量不能为空",
    trigger: "change"
  },
  category: {
    required: true,
    message: "分类不能为空",
    trigger: "change"
  }
};
const cascader = reactive([]);
const ManyList = reactive([]);
const OnlyList = reactive([]);
const ManyAttrList = reactive([]);
const FrominpRef = reactive({});
const Frominp = reactive({
  name: "",
  price: 0,
  weight: 0,
  number: 0,
  category: "",
  picacg: [],
  introduce: ""
});
const cascaderprops = {
  expandTrigger: "hover",
  label: "cat_name",
  value: "cat_id",
  children: "children"
  // emitPath: false
};
// 获取动态参数和静态属性
function getCateManyList() {
  // 获取动态参数
  getCateAttrs({
    id: Frominp.category[Frominp.category.length - 1],
    sel: "many"
  }).then(res => {
    console.log(res);
    if (res.meta.status == 200) {
      ManyList.splice(0, 1000);
      ElMessage.success(res.meta.msg);
      ManyList.push(...res.data);
    } else {
      ElMessage.error("获取动态参数失败");
    }
  });
}
function getCateOnlyList() {
  // 获取静态属性
  getCateAttrs({
    id: Frominp.category[Frominp.category.length - 1],
    sel: "only"
  }).then(res => {
    console.log(res);
    if (res.meta.status == 200) {
      OnlyList.splice(0, 1000);
      ElMessage.success(res.meta.msg);
      OnlyList.push(...res.data);
    } else {
      ElMessage.error("获取静态属性失败");
    }
  });
}
// tab切换时同时切换进度条
function checkthere(i) {
  activeKey.value = Number(i - 1);
}
const handleChange = value => {
  console.log(value);
  getCateOnlyList();
  getCateManyList();
};
// 图片上传
const headersObj = {
  Authorization: window.sessionStorage.getItem("token")
};
const previewPath = ref("");
const previewDialogVisible = ref(false);
function handlePreview(file) {
  previewPath.value = file.response.data.url;
  previewDialogVisible.value = true;
}
function handleSuccess(resposne) {
  const picInfo = { pic: resposne.data.tmp_path };
  Frominp.picacg.push(picInfo);
}
function handleRemove(file) {
  const filePath = file.response.data.tmp_path;
  const index = Frominp.picacg.findIndex(x => x.pic === filePath);
  Frominp.picacg.splice(index, 1);
}

// tab切换守卫
function beforeTabLeave(newName, oldName) {
  if ((newName == "2" || newName == "3") && Frominp.category.length == 0) {
    ElMessage.error("请先选择商品分类!");
    return false;
  }
}
const SubmitSay = ref(false);
function SubmitFrom(from) {
  console.log(from);
  from.validate(flag => {
    if (flag) {
      let query = {
        attrs: [],
        goods_name: Frominp.name,
        goods_price: Frominp.price,
        goods_number: Frominp.number,
        goods_weight: Frominp.weight,
        pics: Frominp.picacg,
        goods_cat: Frominp.category.join(","),
        introduce: Frominp.introduce.ops && Frominp.introduce.ops[0].insert
      };
      // 处理动态参数
      ManyList.forEach(item => {
        const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals };
        query.attrs.push(newInfo);
      });
      // 处理静态参数
      OnlyList.forEach(item => {
        const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals };
        query.attrs.push(newInfo);
      });
      console.log(query);
      postaddGoods(query).then(res => {
        console.log(res);
        if (res.meta.status == 201) {
          ElMessage.success(res.meta.msg);
          SubmitSay.value = true;
          setTimeout(() => {
            router.push("/goods");
          }, 3000);
        } else {
          ElMessage.success("添加商品失败");
        }
      });
    } else {
      return;
    }
  });
}
onBeforeMount(() => {
  getCategories().then(res => {
    console.log(res.data);
    cascader.push(...res.data);
  });
});
</script>

<style scoped>
.sidebar {
  height: 600px;
  width: 120px;
}
.box {
  display: flex;
}
.main {
  width: calc(100% - 120px);
}
.main .QuillEditor {
  height: calc(100vh - 400px);
}
.subtitle {
  font-size: 24px;
  color: #979797;
}
.subtitle p {
  margin-bottom: 20px;
}
</style>